<template>
  <div id="role-page" class="role-page">
    <div class="content-wrap">
      <div class="show-auth">
        <div class="information" v-if="show==='sign'">
          点击角色可查看相应权限
        </div>
        <!-- <div id="dealRole" class="dealRole" v-if="show==='dealRole'">
          <p class="deal-title">{{type === 'add'? '添加角色': '编辑角色'}}</p>
          <div class="dealRole-content">
            <at-form ref="role" class="form" :model="role" :rules="roleRule">
            <at-form-item prop="role_name" project="mh">
              <div class="title">角色名称：</div>
              <div class="role-name-wrap">
                <at-input v-model="role.role_name"></at-input>
              </div>
            </at-form-item>
            <at-form-item>
              <div class="auth">
                <div class="title auth-name">功能授权：</div>
                <div class="authlist">
                  <at-tree
                  ref="tree"
                  :data="listData"
                  :props="props"
                  nodeKey="id"
                  :defaultCheckedKeys="checked"
                  showCheckbox
                  defaultExpandAll
                  >
                  </at-tree>
                </div>
                <div class="bottom-btn">
                  <at-button type="primary" @click="confirmEvent">确认</at-button>
                  <at-button @click="cancelEvent">取消</at-button>
                </div>
              </div>
            </at-form-item>
          </at-form>
          </div>
        </div> -->
        <div class="auth-list-wrap" v-if="show==='list'">
          <p class="big-title">用户角色权限</p>
          <div class="authlist" v-loading="loading" element-loading-text="拼命加载中">
          <div class="role">
            <span class="title">角色名称：</span>
            <span>{{roleName}}</span>
          </div>
          <div class="auth">
            <span class="title">权限列表：</span>
            <div class="list">
              <at-tree
              :data="roles_group"
              :props="props"
              nodeKey="role_id"
              defaultExpandAll
              >
              </at-tree>
            </div>
          </div>
          </div>
        </div>
      </div>
      <div class="show-table">
        <div class="show-table-content">
          <div class="table-title">角色管理列表</div>
          <div class="top-tool">
          <div class="add-btn">
            <!-- <at-button @click="addRole" type="primary"><i class="saas-icon-ten"></i>新增</at-button> -->
            <!-- <at-button @click="test">test</at-button>
            名字<at-input v-model="testValue1"></at-input>
            id<at-input v-model="testValue2"></at-input> -->
            <div class="change-btn">
              <at-button @click="changeInfo" type="primary" size="bigger">
                <i class="saas-icon-page-refresh" style="position:relative;top:2px"></i>
                查看同步信息  
              </at-button>
              <span v-if="count>0" :class="{'doubleNum':count.toString().length === 2, 'singleNum': count.toString().length === 1, 'more': count>99, 'common': true}">  
                <span class="infoCount" v-if="count<=99"> {{count}}</span>  
                <span class="infoCount" v-else>99+</span>
              </span>

            </div>
            <div class="search">
              <at-search v-model="searchValue" placeholder="请输入用户角色名" type="text" project='mh' @keyup.enter.native="searchEvent" icon="search" :on-icon-click="searchEvent"/>
            </div>
          </div>
        </div>
        <div class="table-wrap">
          <at-table @cell-click="cellClick" :data="tableData.dataSource" width="100%" :border="false">
            <at-table-column align="left" prop="arole_name" label="用户角色名"  min-width="20"
            ></at-table-column>
            <at-table-column align="left" prop="data_source" label="来源" min-width="20"></at-table-column>
            <at-table-column align="left" prop="update_time" label="最后一次修改时间" min-width="20"></at-table-column>
            <at-table-column align="left" prop="bperson_name" label="修改人" min-width="20"></at-table-column>
            <!-- <at-table-column label="操作" align='left' min-width="20">
              <template slot-scope="scope">
                <i class="saas-icon-pencil" style="fontSize:20px;color: rgb(31, 146, 239);lineHeight:40px" @click.stop="editRole(scope.$index, scope.row)"></i>
                <i class="saas-icon-del" style="fontSize:20px;color: rgb(31, 146, 239);lineHeight:40px" @click.stop="deleteRole(scope.$index, scope.row)">
                </i>
              </template>
            </at-table-column> -->
        </at-table> 
        </div>
        <div class="page">
          <Pagination :currentPage="tableData.current" :total="tableData.total" :pageSizes="[20, 40, 60, 80]" :pageSize="tableData.pageSize" layout="slot, total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          </Pagination>
        </div>
        </div>
      </div>
      <!-- <at-dialog title='提示' :visible.sync='deleteDialogVisible' size='tiny'>
        <div class="dialog__body__content">
          确认删除
        </div>
        <div slot='footer' class='dialog-footer'>
          <at-button type='primary' @click.stop='deleteConfirm'>确 定</at-button>
          <at-button @click.stop='deleteCancel'>取 消</at-button>
        </div>
      </at-dialog> -->
    </div>
  </div>
</template>
<script>
import $http from '../../../../utils/http.js'
import { mapActions, mapMutations, mapGetters } from 'vuex'
export default{
  name: 'role',
  data () {
    // 角色名称校验数字
    const validRoleName = (rule, value, callback) => {
      // 去除前后空格
      let Value = value.replace(/(^\s*)|(\s*$)/g, '')
      const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+$/
      if (Value) {
        setTimeout(() => {
          if (reg.test(Value)) {
            this.baseSearch.search.value = Value
            $http.option('/api/auth/roles', this.baseSearch).then(({ status, data }) => {
              if (status === 'success') {
                let flag = false // 表示库中没有此角色名称
                if (data.total !== 0) {
                  for (let obj of data.dataSource) {
                    if (Value === obj.arole_name) {
                      flag = true
                      break
                    }
                  }
                }
                // 库中没有此角色
                if (!flag) {
                  callback()
                } else {
                  if (this.type === 'add') {
                    callback(new Error('角色名不能重复'))
                  } else {
                    if (Value === this.rawName) {
                      callback()
                    } else {
                      callback(new Error('角色名不能重复'))
                    }
                  }
                }
              } else if (status === 'fail') {
                this.$notify.error({
                  title: '获取用户角色权限列表失败'
                })
                callback()
              } else if (status === 'notallow') {
                this.$notify.error({
                  title: '没有权限'
                })
              }
            })
          } else {
            callback(new Error('只能输入数字、汉字、英文'))
          }
        }, 500)
      } else {
        callback(new Error('只能输入数字、汉字、英文'))
      }
    }
    return {
      total: 4,
      type: '',
      role: {
        role_name: ''
      },
      // 角色名称编辑前
      rawName: '',
      role_id: '',
      // 勾选项
      checked: [],
      props: {
        label: 'label',
        children: 'children'
      },
      // 人工录入表单校验
      roleRule: {
        role_name: [
          {
            required: true,
            message: '角色名不能为空',
            trigger: 'blur'
          },
          { validator: validRoleName, trigger: 'blur' }
        ]
      },
      // 搜索框输入值
      searchValue: '',
      // 指控右侧显示提示信息或权限列表
      show: 'sign',
      // 判断用户角色名和权限是否有改动
      role_name: '',
      list: [],
      // 删除提示对话框
      deleteDialogVisible: false,
      // 删除行号
      rowIndex: '',
      testValue1: '',
      testValue2: '',
      baseSearch: {
        'pagination': {
          'current': 1, // 当前页码
          'pageSize': 20 // 当前页显示的数据条数
        },
        'search': {
          'value': '' // 需要模糊搜索的值（搜索框）
        }
      }
    }
  },
  computed: {
    ...mapGetters('role', [
      'roles_group',
      'loading',
      'id',
      'name',
      'tableData',
      'count'
    ]),
    listData () {
      return this.list
    },
    roleName: {
      get () {
        return this.name
      },
      set (value) {
        return this.SET_ROLE_NAME(value)
      }
    }
  },
  methods: {
    // test () {
    //   let ids = ["lonction_37", "lonction_36"]
    //   let data = {
    //     role_id: this.testValue2,
    //     role_name: this.testValue1,
    //     group_ids: JSON.stringify(ids),
    //     r_person: 'location_2'
    //   }
    //   $http.post('/api/sync/role/add', data).then(({ status, data }) => {
    //     if (status === 'success') {
    //       console.log('成功')
    //     } else {
    //       this.$notify({
    //         message: '删除成功！',
    //         type: 'success'
    //       })
    //     }
    //   })
    // },
    ...mapActions('role', [
      'GET_ROLE_LIST',
      'GET_ROLES_GROUP',
      'DELETE_ROLE',
      'ADD_ROLE',
      'UPDATE_ROLES_GROUP',
      'GET_COUNT',
      'GET_SYNC_ADD',
      'GET_SYNC_UPDATE',
      'GET_SYNC_DELETE'
    ]),
    ...mapMutations('role', [
      'SET_ROLE_LIST',
      'SET_ROLES_GROUP',
      'SET_ROLE_ID',
      'SET_ROLE_NAME'
    ]),
    handleSizeChange (value) {
      this.tableData.pageSize = value
      this.baseSearch.pagination.pageSize = value
      this.GET_ROLE_LIST(JSON.stringify(this.baseSearch))
    },
    handleCurrentChange (value) {
      this.tableData.current = value
      this.baseSearch.pagination.current = value
      this.GET_ROLE_LIST(JSON.stringify(this.baseSearch))
    },
    cellClick (row, event) {
      this.GET_ROLES_GROUP(row.arole_id)
      this.roleName = row.arole_name
      this.show = 'list'
    },
    // 获取权限列表和具有权限的id集合
    getList (sendData) {
      $http.post('/api/auth/roles/add', sendData).then(({ status, data } = {}) => {
        if (status === 'success') {
          this.role.role_name = data.role_name
          this.list = data.result
          this.checked = data.group_ids
        } else {
          this.$notify.error({
            title: '获取权限列表失败'
          })
        }
      })
    },
    // 搜索角色
    searchEvent () {
      if (this.searchValue !== '') {
        this.baseSearch.search.value = this.searchValue
        this.GET_ROLE_LIST(this.baseSearch)
      } else {
        this.baseSearch.search.value = ''
        this.GET_ROLE_LIST(this.baseSearch)
      }
    },
    // 变更信息
    changeInfo () {
      this.GET_SYNC_ADD()
      this.GET_SYNC_UPDATE()
      this.GET_SYNC_DELETE()
      this.$router.push({ name: '角色变更信息列表' })
    }
    // addRole () {
    //   this.show = 'dealRole'
    //   this.type = 'add'
    //   this.role.role_name = ''
    //   this.checked = []
    //   this.getList({})
    // },
    // // 添加角色
    // confirmEvent () {
    //   this.$refs['role'].validate(valid => {
    //     if (valid) {
    //       // 选中的节点，包括子节点的父节点
    //       let sendData = []
    //       let arr = new Set()
    //       let ids = this.$refs.tree.getCheckedKeys()
    //       for (let i of this.listData) {
    //         if (i.children !== undefined && i.children !== null && i.children.length > 0) {
    //           for (let j of i.children) {
    //             if (j.children !== undefined && j.children !== null && j.children.length > 0) {
    //               for (let k of j.children) {
    //                 if (ids.indexOf(k.id) > -1) {
    //                   arr.add(k.id)
    //                   arr.add(j.id)
    //                   arr.add(i.id)
    //                 }
    //               }
    //             } else {
    //               if (ids.indexOf(j.id) > -1) {
    //                 arr.add(j.id)
    //                 arr.add(i.id)
    //               }
    //             }
    //           }
    //         } else {
    //           if (ids.indexOf(i.id) > -1) {
    //             arr.add(i.id)
    //           }
    //         }
    //       }
    //       let roleName = this.role.role_name.replace(/(^\s*)|(\s*$)/g, '')
    //       if (this.type === 'add') {
    //         this.baseSearch.search.value = ''
    //         sendData = {
    //           'group_ids': JSON.stringify([...arr]),
    //           'role_name': roleName
    //         }
    //         this.ADD_ROLE({ sendData: sendData, baseSearch: this.baseSearch })
    //       } else {
    //         this.baseSearch.search.value = ''
    //         sendData = {
    //           'group_ids': JSON.stringify([...arr]),
    //           'role_name': roleName,
    //           'role_id': this.role_id
    //         }
    //         this.UPDATE_ROLES_GROUP({ sendData: sendData, baseSearch: this.baseSearch })
    //       }
    //       this.show = 'list'
    //     } else {
    //       return false
    //     }
    //   })
    // },
    // // 取消添加
    // cancelEvent () {
    //   this.show = 'sign'
    // },
    // // 编辑角色
    // editRole (index, row) {
    //   this.show = 'dealRole'
    //   this.type = 'edit'
    //   this.role_id = row.arole_id
    //   this.role.role_name = row.arole_name
    //   this.rawName = row.arole_name
    //   let sendData = {
    //     role_id: row.arole_id,
    //     role_name: row.arole_name
    //   }
    //   this.getList(sendData)
    // },
    // // 确定删除
    // deleteConfirm () {
    //   this.deleteDialogVisible = false
    //   this.baseSearch.search.value = ''
    //   this.DELETE_ROLE({ role_id: this.tableData.dataSource[this.rowIndex]['arole_id'], baseSearch: this.baseSearch })
    //   this.show = 'sign'
    // },
    // // 取消删除
    // deleteCancel () {
    //   this.deleteDialogVisible = false
    // },
    // // 删除此角色
    // deleteRole (index, row) {
    //   this.deleteDialogVisible = true
    //   this.rowIndex = index
    // }
  },
  created () {
    this.GET_COUNT()
    this.GET_ROLE_LIST(JSON.stringify(this.baseSearch))
  }
}
</script>
<style>
#role-page .at-dialog__body {
  position: relative;
}
#role-page .top-tool {
  padding: 10px 20px 0;
}
#role-page  .content-wrap{
  overflow: hidden;
}
#role-page .show-table {
  background: #ECF0F5;
  padding-right: 20px;
  margin-right: 478px;
}
#role-page .show-table-content {
  background: #fff;
  padding: 0 0px 20px;
  border-top: none;
}
#role-page .add-btn {
  background: #fff;
}
#role-page .search {
  float: right;
}
#role-page  .show-auth {
  padding: 0px;
  background: #fff;
  width: 478px;
  float: right;
  border: 1px solid #eee;
  border-top: none;
}
#role-page .auth .title {
  vertical-align: top;
}
#role-page .role {
  padding: 20px 20px;
}
#role-page .list {
  width: 376px;
  float: right;
  margin-top: -8px;
  margin-bottom: 20px;
}
#role-page .big-title {
  border-bottom: 1px solid #eee;
  font-size: 12px;
  height: 50px;
  color: #5c6781;
  font-size: 14px;
  line-height: 50px;
  padding-left: 20px;
  margin: 0px;
  font-weight: bold;
}
#role-page .at-tree__empty-text {
  width: 100%;
  margin-top: -13px;
  font-size: 12px;
  text-align: left;
  padding-left: 6px;
  color: #758697;
}
#role-page .at-tree__empty-block {
  position: relative;
  min-height: 20px;
  text-align: center;
  top: 21px;
  width: 100%;
  height: 100%;
}
#dealRole {
  padding: 0px 0 !important;
  color: #5C6781;
  background: #fff;
  font-size: 12px;
}
#dealRole .title, .auth-name, .authlist {
  display: inline-block;
  font-size: 12px;
}
#dealRole .auth-name {
  vertical-align: top;
}
#dealRole .at-form-item {
  margin-bottom: 0px;
  margin-top: 0px;
}
#dealRole .auth {
  margin-top: 10px !important;
}
#dealRole .bottom-btn {
  padding-left: 115px;
  padding-bottom: 20px;
}
#dealRole .at-form-item__error {
  margin-left: 70px;
}
.show-table .at-table__body-wrapper{
  overflow: hidden !important;
}
#dealRole .at-form-item:last-child {
  border-top: none;
}
.at-table .at-table__header-wrapper .at-table__header thead th>.cell {
  font-family: "\5B8B\4F53" !important;
}
#dealRole .at-form-item__content {
  text-align: left;
}
</style>
<style scoped>
.dialog__body__content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);
}
#dealRole #count {
  display: inline-block;
  border: 1px solid rgb(255, 52, 49);
  border-radius: 10px;
  height: 22px;
  padding: 2px 7px;
  font-size: 12px;
  font-family: '宋体';
  background: #ff4949;
  line-height: 18px;
  margin-left: 7px;
  transform: scale(0.8);
  color: rgba(255, 255, 255, 1);
}
.saas-icon-ten, .saas-icon-page-refresh{
  font-size: 20px;
  vertical-align: -4px;
  margin-right: -1px;
}
.saas-icon-ten {
  margin-right: 5px;
}
.page{
  margin-top: 20px;
  padding-bottom: 20px;
  text-align: center;
  height: 30px;
}
#dealRole .authlist {
  overflow: auto;
  width: 376px;
  float: right;
  margin-right: 20px;
  margin-bottom: 20px;
}
.change-btn {
  display: inline-block;
}
.doubleNum {
  width: 25px;
  margin-top: 4px;
  border-radius: 8.5px;
}
.singleNum {
  width: 17px;
  border-radius: 50%;
  top: -15px;
  position: relative;
  left: -14px;
}
.more {
  width: 32px;
  border-radius: 8.5px;
}
.common {
  font-weight: bold;
  background: #1f92ef;
  display: inline-block;
  height: 17px;
  position: relative;
  left: -14px;
  top: -15px;
}
.infoCount {
  display: block;
  color: #FFFFFF;
  height: 17px;
  line-height: 18px;
  text-align: center;
  font-size : 10px;
  font-family: '宋体';
  -webkit-transform : scale(0.84,0.84) ;
  *font-size:10px;
}
.information {
  height: 50px;
  line-height: 50px;
  padding-left: 20px;
}
.auth {
  padding-left: 20px;
}
.deal-title {
  padding-left: 20px;
  margin: 0px;
  height: 50px;
  font-weight: bold;
  color: #5c6781;
  font-size: 14px;
  line-height: 50px;
  border-bottom: 1px solid #eee;
}
.dealRole-content {
  padding-left: 20px;
}
.dealRole-content .auth {
  padding-left: 0px;
}
.role-name-wrap {
  margin-right: 20px;
  display: inline-block;
  width: 369px;
}
.table-title {
  font-weight: bold;
  height: 50px;
  color: #5c6781;
  font-size: 14px;
  padding-left: 20px;
  line-height: 50px;
  border-bottom: 1px solid #eee;
}
.table-wrap {
  padding: 0 20px
}
</style>